//
//  BuyProductViewController.m
//  cherryproduct
//
//  Created by umessage on 14-8-18.
//  Copyright (c) 2014年 cherry. All rights reserved.
//

#import "BuyProductViewController.h"
#import "ProductReviewViewController.h"
#import "SGBuyPageViewController.h"

@interface BuyProductViewController ()<UIWebViewDelegate, UMSocialUIDelegate>

@property(nonatomic, strong) UIView * bar_view_bb;

@property(nonatomic, strong) UIButton * btn_buy_more;
@property(nonatomic, strong) UILabel * label_time;

@property(nonatomic, strong) NSTimer * time_out;

@property(nonatomic, strong) UIButton * btn_buy_join;
@property(nonatomic, assign) BOOL m_b_is_beco;

@property(nonatomic, assign) BOOL m_b_is_pic;

@property(nonatomic, assign) BOOL m_b_is_ajax;

//share
@property(nonatomic, strong) NSString * str_share_url_address;

@end

@implementation BuyProductViewController

@synthesize stringid;
@synthesize stringurl;

static NSString * JSHandler;

+ (void)initialize {
    JSHandler = [NSString stringWithContentsOfURL:[[NSBundle mainBundle] URLForResource:@"industry" withExtension:@"json"]
                                         encoding:NSUTF8StringEncoding
                                            error:nil];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)dealloc
{
    if ([self.time_out isValid]) {
        [self.time_out invalidate];
    }
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self setTitle:@"商品详情"];
    [self addNavBarButton:RIGHT_SHARE_MESSAGE];
    
    {
        NSData * cookiesdata = [[NSUserDefaults standardUserDefaults] objectForKey:kUserDefaultsCookie];
        if([cookiesdata length]) {
            NSArray *cookies = [NSKeyedUnarchiver unarchiveObjectWithData:cookiesdata];
            NSHTTPCookie *cookie;
            for (cookie in cookies) {
                [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
            }
        }
    }
    //@"http://42.120.48.241/api.php/groupon/groupon_buy_comment/id/%@"
    NSString * str_url = @"http://cherry8.com/api.php/groupon/groupon_buy_comment/id/";
    //NSString * str_url = @"http://180.150.179.226/cherry/api.php/groupon/groupon_buy_comment/id/";
    
    self.stringurl = [NSString stringWithFormat:@"%@%@", str_url, self.stringid];
    self.str_share_url_address = self.stringurl;
    
    if (webview==nil) {
        webview = [[UIWebView alloc] initWithFrame:self.myView.bounds];
        webview.backgroundColor=[UIColor whiteColor];
        webview.delegate=self;
        [self.myView addSubview:webview];
    }
    NSURLRequest * request =[NSURLRequest requestWithURL:[NSURL URLWithString:self.stringurl]];
    [webview loadRequest:request];
    
    // Do any additional setup after loading the view.
    CGFloat height = self.myView.frame.size.height;
    CGFloat width = self.myView.frame.size.width;
    
    if (self.m_b_is_come_s){
        self.bar_view_bb = [[UIView alloc] initWithFrame:CGRectMake(0, height-64, width, 64)];
        self.bar_view_bb.backgroundColor=[UIColor clearColor];
        [self.myView addSubview:self.bar_view_bb];
        
        {
            //显示钱
            UILabel * la = [[UILabel alloc] initWithFrame:CGRectMake(5, 7, 10, 34)];
            la.backgroundColor=[UIColor clearColor];
            la.textColor=[UIColor redColor];
            la.font=[UIFont systemFontOfSize:12];
            la.textAlignment=NSTextAlignmentCenter;
            la.text=@"¥";
            [self.bar_view_bb addSubview:la];
            
            la = [[UILabel alloc] initWithFrame:CGRectMake(5, 0, 85, 44)];
            la.backgroundColor=[UIColor clearColor];
            la.textColor=[UIColor redColor];
            la.font=[UIFont systemFontOfSize:20];
            la.textAlignment=NSTextAlignmentCenter;
            if (self.str_money && [self.str_money isKindOfClass:[NSString class]]) {
                la.text=self.str_money;
            } else {
                la.text=@"0";
            }
            
            [self.bar_view_bb addSubview:la];
        }
        {
            self.btn_buy_more = [[UIButton alloc] initWithFrame:CGRectMake(width-60, 0, 44, 64)];
            self.btn_buy_more.backgroundColor=[UIColor clearColor];
            [self.bar_view_bb addSubview:self.btn_buy_more];
            
            UIImageView * imagevv = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"goodsmore"]];
            imagevv.frame=CGRectMake(0, 5, 34, 34);
            [self.btn_buy_more addSubview:imagevv];
            
            UILabel * la = [[UILabel alloc] initWithFrame:CGRectMake(0, 39, 34, 25)];
            la.backgroundColor=[UIColor clearColor];
            la.textColor=[UIColor grayColor];
            la.font=[UIFont systemFontOfSize:12];
            la.textAlignment=NSTextAlignmentCenter;
            la.text=@"更多";
            [self.btn_buy_more addSubview:la];
            
            [self.btn_buy_more addTarget:self action:@selector(doActionMoreData:) forControlEvents:UIControlEventTouchUpInside];
        }
        
        {
            self.btn_buy_join = [[UIButton alloc] initWithFrame:CGRectMake(90, 0, width-180, 44)];
            self.btn_buy_join.backgroundColor=[UIColor clearColor];
            UIImageView * image_bb_v = [[UIImageView alloc] initWithFrame:CGRectMake(0, 5, width-180, 34)];
            image_bb_v.backgroundColor=[UIColor redColor];
            image_bb_v.layer.cornerRadius = 15;//设置那个圆角的有多圆
            image_bb_v.layer.borderWidth = 0;//设置边框的宽度，当然可以不要
            image_bb_v.layer.borderColor = [RGBCOLOR(242, 187, 159) CGColor];//设置边框的颜色
            image_bb_v.layer.masksToBounds = YES;//设为NO去试试
            image_bb_v.alpha=0.7;
            [self.btn_buy_join addSubview:image_bb_v];
            UILabel * label_ti = [[UILabel alloc] initWithFrame:CGRectMake(0, 5, width-180, 34)];
            label_ti.backgroundColor=[UIColor clearColor];
            label_ti.textAlignment=NSTextAlignmentCenter;
            label_ti.text=@"立即参团";
            label_ti.font=[UIFont systemFontOfSize:18];
            label_ti.textColor=[UIColor whiteColor];
            [self.btn_buy_join addSubview:label_ti];
            
            [self.bar_view_bb addSubview:self.btn_buy_join];
            
            [self.btn_buy_join addTarget:self action:@selector(doActionSenderGo:) forControlEvents:UIControlEventTouchUpInside];
        }
        
        {
            self.label_time = [[UILabel alloc] initWithFrame:CGRectMake(50, 44, width-100, 14)];
            self.label_time.textColor = [UIColor blackColor];
            self.label_time.backgroundColor = [UIColor clearColor];
            self.label_time.font = [UIFont systemFontOfSize:9];
            self.label_time.textAlignment = NSTextAlignmentCenter;
            self.label_time.text = @"本次团购剩余时间:0:0:0";
            [self.bar_view_bb addSubview:self.label_time];
            
            if (self.end_time > 0) {
                [self getStartAction];
            } else {
                self.label_time.text = @"团购已经结束";
            }
            
        }
    }
}

- (void)doActionMoreData:(UIButton*)sender
{
    if (self.str_group_id && [self.str_group_id isKindOfClass:[NSString class]]) {
        FIGoodsDetailsViewController * vc = [[FIGoodsDetailsViewController alloc] init];
        vc.str_goods_id = self.str_group_id;
        vc.str_color_bg = @"#FBC900";
        [self.navigationController pushViewController:vc animated:YES];
    } else {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (void)backButtonAction:(UIButton*) sender{
    if (!self.m_b_is_pic) {
        [self.navigationController popViewControllerAnimated:YES];
    } else {
        if ([webview canGoBack]) {
            [webview goBack];
        }
        if (self.m_b_is_come_s){
            self.bar_view_bb.hidden=NO;
        }
        //变更头
        [self setTitle:@"商品详情"];
        [self.navigationBar viewWithTag:121].hidden=NO;
        [self.navigationBar viewWithTag:122].hidden=NO;
    }
}

- (void)doActionSenderGo:(id)sender
{
    {
        NSString * loginInfo = [[LoginViewController shareUserInfo] objectForKey:KEY_HAVE_LOGIN];
        
        if (loginInfo && [loginInfo isKindOfClass:[NSString class]] && [loginInfo isEqualToString:@"1"])
        {

        }
        else
        {
            LoginViewController * vc = [[LoginViewController alloc] init];
            vc.m_is_come_other=YES;
            vc.block_dismiss = ^(NSInteger b) {
                [webview reload];
            };
            [self.navigationController pushViewController:vc animated:YES];
            
            return;
        }
    }
    
    //....
    [self.view startLoadingAnimation];

    NSMutableDictionary * requestDic = [[NSMutableDictionary alloc] initWithCapacity:2];
    [requestDic setObject:self.stringid forKey:@"id"];

    [[HttpNewBaseService sharedClient] getRequestOperation:@"groupon/groupon_buy_log" paramDictionary:requestDic onCompletion:^(NSString *responseString) {
        [self.view stopLoadingAnimation];
        
        NSDictionary * dic = [responseString JSONValue];
        if (dic) {
            NSInteger status = [[dic objectForKey:@"status"] integerValue];
            if (status == 1) {
                //跳转
                NSDictionary * data = [dic objectForKey:@"data"];
                if (data && [data isKindOfClass:[NSDictionary class]]) {
                    NSInteger soldout = [[data objectForKey:@"soldout"] integerValue];
                    if (soldout != 0) {
                        [self showAlertView:@"温馨提示" subtitle:@"抱歉,商品卖光了,等下次吧!"];
                    } else {
                    
                        NSString * str_url = [data objectForKey:@"url"];
                        NSURL * url = nil;
                        if (str_url && [str_url isKindOfClass:[NSString class]]) {
                            url = [[NSURL alloc] initWithString:str_url];
                        } else {
                            url = [[NSURL alloc] initWithString:@"http://www.taobao.com"];
                            str_url=@"http://www.taobao.com";
                        }
                        //[[UIApplication sharedApplication]openURL:url];
                        SGBuyPageViewController * vc = [[SGBuyPageViewController alloc] init];
                        vc.str_url_page=str_url;
                        [self.navigationController pushViewController:vc animated:YES];
                    }
                }
            } else {
                [self showAlertView:@"温馨提示" subtitle:[dic objectForKey:@"message"]];
            }
        }
        
    } onError:^(NSError *error) {
        [self.view stopLoadingAnimation];
        
    } onAnimated:YES];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    /*
    if (webview) {
        [webview removeFromSuperview];
        webview=nil;
    }
    
    if (webview==nil) {
        webview = [[UIWebView alloc] initWithFrame:self.myView.bounds];
        webview.backgroundColor=[UIColor whiteColor];
        webview.delegate=self;
        [self.myView addSubview:webview];
    }
    
    if (self.m_b_is_beco) {//刷新评测页面
        self.stringurl = [NSString stringWithFormat:@"http://42.120.48.241/api.php/groupon/groupon_buy_comment/id/%@",
                          self.stringid];
        self.m_b_is_beco=NO;
        
        NSURLRequest * request =[NSURLRequest requestWithURL:[NSURL URLWithString:self.stringurl]];
        [webview loadRequest:request];
        
    } else if (self.m_b_is_ajax) {
        self.m_b_is_ajax=NO;
        
        if (self.stringurl==nil) {
            self.stringurl = [NSString stringWithFormat:@"http://42.120.48.241/api.php/groupon/groupon_buy_market/id/%@",self.stringid];
        }
        
        NSURLRequest * request =[NSURLRequest requestWithURL:[NSURL URLWithString:self.stringurl]];
        [webview loadRequest:request];
    } else {
        self.stringurl = [NSString stringWithFormat:@"http://42.120.48.241/api.php/groupon/groupon_buy_comment/id/%@",self.stringid];
        
        NSURLRequest * request =[NSURLRequest requestWithURL:[NSURL URLWithString:self.stringurl]];
        [webview loadRequest:request];
    }*/
    
    if (self.m_b_is_come_s) {
        [self.myView bringSubviewToFront:self.bar_view_bb];
    }
}


-(void)messageButtonAction:(UIButton*)button
{
    if (self.m_b_is_have_say) {
        [self showAlertView:@"温馨提示" subtitle:@"不能重复评论!"];
        return;
    }
    
    NSString * loginInfo = [[LoginViewController shareUserInfo] objectForKey:KEY_HAVE_LOGIN];
    
    if (loginInfo && [loginInfo isKindOfClass:[NSString class]] && [loginInfo isEqualToString:@"1"])
    {
        ProductReviewViewController* review = [[ProductReviewViewController alloc] init];
        review.str_id = self.stringid;
        review.block_dismiss = ^(NSInteger b) {
            if (self.m_b_is_beco) {
                [webview reload];
                self.m_b_is_beco=NO;
                self.m_b_is_have_say=YES;
            }
        };
        [self.navigationController pushViewController:review animated:YES];
    } else {
        LoginViewController * vc = [[LoginViewController alloc] init];
        vc.m_is_come_other=YES;
        vc.block_dismiss = ^(NSInteger b) {
            [webview reload];
        };
        [self.navigationController pushViewController:vc animated:YES];
    }
}


-(void)shareButtonAction:(UIButton*)button
{
    NSString * str_send_info = [NSString stringWithFormat:@"樱桃优品--%@  %@ ", self.str_share_name, self.str_share_url_address];
//    [UMSocialWechatHandler setWXAppId:@"wx42bae2a079770c21"
//                            appSecret:@"85762a1a96144f320249c0e3416074fe"
//                                  url:str_send_info];
    NSString * str_send_share_weixin = [NSString stringWithFormat:@"樱桃优品--%@ ", self.str_share_name];
    //樱桃优品  用心为您选择
    [UMSocialData defaultData].extConfig.wxMessageType = UMSocialWXMessageTypeApp;

    /*
    [[UMSocialData defaultData].extConfig.wechatTimelineData.urlResource setResourceType:UMSocialUrlResourceTypeImage url:self.str_share_img_url]; //设置微信朋友圈分享视频
    
    [[UMSocialData defaultData].extConfig.sinaData.urlResource setResourceType:UMSocialUrlResourceTypeImage url:self.str_share_img_url];
    */
    [UMSocialData defaultData].extConfig.title = str_send_share_weixin;//self.str_share_name;
    [UMSocialData defaultData].extConfig.wechatSessionData.url = self.str_share_url_address;
    [UMSocialData defaultData].extConfig.wxMessageType=UMSocialWXMessageTypeWeb;
    
    [UMSocialData defaultData].extConfig.wechatSessionData.shareText=[NSString stringWithFormat:@"樱桃优品 用心为您选择"];
    
    [UMSocialData defaultData].extConfig.wechatTimelineData.url = self.str_share_url_address;
    
    [UMSocialSnsService presentSnsIconSheetView:self
                                         appKey:@"53fc9df6fd98c5c9a0009069"
                                      shareText:str_send_info
                                     shareImage:self.image_share_
                                shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina, UMShareToWechatSession, UMShareToWechatTimeline, nil]
                                       delegate:self];
}
//实现回调方法（可选）：
-(void)didFinishGetUMSocialDataInViewController:(UMSocialResponseEntity *)response
{
    //根据responseCode得到发送结果,如果分享成功
    if(response.responseCode == UMSResponseCodeSuccess)
    {
        //得到分享到的微博平台名
        NSLog(@"share to sns name is %@",[[response.data allKeys] objectAtIndex:0]);
    }
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
#pragma mark -
#pragma mark UIWebViewDelegate
- (void)webViewDidStartLoad:(UIWebView *)webView;
{
    [self.view startLoadingAnimation];
}
- (void)webViewDidFinishLoad:(UIWebView *)webView;
{
    [self.view stopLoadingAnimation];
    
    [webView stringByEvaluatingJavaScriptFromString:JSHandler];
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error;
{
    [self.view stopLoadingAnimation];
}

#define CocoaJSHandler @"mpajaxhandler"

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType;
{
    //抓取ajax
    if ([[[request URL] scheme] isEqual:CocoaJSHandler]) {
        //NSString * requestedURLString = [[[request URL] absoluteString] substringFromIndex:[CocoaJSHandler length] + 3];
        
        //NSLog(@"ajax request: %@", requestedURLString);
        
        NSString * loginInfo = [[LoginViewController shareUserInfo] objectForKey:KEY_HAVE_LOGIN];
        
        if (loginInfo && [loginInfo isKindOfClass:[NSString class]] && [loginInfo isEqualToString:@"1"])
        {
            return YES;
        }
        else
        {
            LoginViewController * vc = [[LoginViewController alloc] init];
            vc.m_is_come_other=YES;
            vc.block_dismiss = ^(NSInteger b) {
                [webview reload];
            };
            [self.navigationController pushViewController:vc animated:YES];
            
            self.m_b_is_ajax=YES;
        }
        
        return NO;
    }
    
    //评测界面
    NSRange foundObj = [request.URL.absoluteString rangeOfString:@"groupon_buy_comment" options:NSCaseInsensitiveSearch];
    if(foundObj.length>0) {
        self.m_b_is_beco=YES;
        
        //@"http://42.120.48.241/api.php/groupon/groupon_buy_comment/id/"
        NSString * str_url = @"http://cherry8.com/api.php/groupon/groupon_buy_comment/id/";
        //NSString * str_url = @"http://180.150.179.226/cherry/api.php/groupon/groupon_buy_comment/id/";
        
        self.str_share_url_address = [NSString stringWithFormat:@"%@%@", str_url, self.stringid];
    } else {
        self.m_b_is_beco=NO;
        
        //@"http://42.120.48.241/api.php/groupon/groupon_buy_market/id/"
        NSString * str_url = @"http://cherry8.com/api.php/groupon/groupon_buy_market/id/";
        //NSString * str_url = @"http://180.150.179.226/cherry/api.php/groupon/groupon_buy_market/id/";
        
        self.str_share_url_address = [NSString stringWithFormat:@"%@%@",str_url,self.stringid];
    }
    
    //查看大图
    NSRange foundObj_groupon_buy_pic = [request.URL.absoluteString rangeOfString:@"groupon_buy_pic" options:NSCaseInsensitiveSearch];
    if (foundObj_groupon_buy_pic.length > 0) {
        //在查看大图界面
        self.m_b_is_pic=YES;
        
        if (self.m_b_is_come_s){
            self.bar_view_bb.hidden=YES;
        }
        //变更头
        [self setTitle:@"大图浏览"];
        [self.navigationBar viewWithTag:121].hidden=YES;
        [self.navigationBar viewWithTag:122].hidden=YES;
    } else {
        self.m_b_is_pic=NO;
    }

    return YES;
}

#pragma mark -
#pragma mark time
- (void)getStartAction
{
    double timetemp = self.end_time - [[NSDate date] timeIntervalSince1970];
    NSDateFormatter * fortimemat = [[NSDateFormatter alloc] init];
    [fortimemat setDateFormat:@"HH:mm:ss"];
    
    NSTimeInterval time = timetemp;
    int days=(time)/(3600*24);
    int doutime = time - days*(3600*24);
    int hours=doutime/3600;
    int mont = (doutime%3600)/60;
    int sec = (doutime%3600)%60;
    
    NSString * dateContent = [[NSString alloc] initWithFormat:@"%d:%d:%d", days*24+hours, mont, sec];
    if (sec < 10) {
        dateContent = [[NSString alloc] initWithFormat:@"%d:%d:0%d", days*24+hours, mont, sec];
    }
    
    if (timetemp > 0) {
        self.label_time.text = [NSString stringWithFormat:@"团购剩余时间:%@", dateContent];
        
        self.time_out = [NSTimer scheduledTimerWithTimeInterval:1.0
                                                         target:self
                                                       selector:@selector(timeoverdown:)
                                                       userInfo:nil
                                                        repeats:YES];
    } else {
        self.label_time.text = @"团购已经结束";
    }
}

- (void)timeoverdown:(NSTimer*)timertemp //倒计时
{
    double timetemp = self.end_time - [[NSDate date] timeIntervalSince1970];
    NSDateFormatter * fortimemat = [[NSDateFormatter alloc] init];
    [fortimemat setDateFormat:@"HH:mm:ss"];
    
    NSTimeInterval time = timetemp;
    int days=(time)/(3600*24);
    int doutime = time - days*(3600*24);
    int hours=doutime/3600;
    int mont = (doutime%3600)/60;
    int sec = (doutime%3600)%60;
    
    NSString * dateContent = [[NSString alloc] initWithFormat:@"%d:%d:%d", days*24+hours, mont, sec];
    if (sec < 10) {
        dateContent = [[NSString alloc] initWithFormat:@"%d:%d:0%d", days*24+hours, mont, sec];
    }
    
    if(timetemp>0) {
        self.label_time.text = [NSString stringWithFormat:@"团购剩余时间:%@", dateContent];
    } else {
        self.label_time.text = @"团购已经结束";
        [self.time_out invalidate];
    }
}

@end























